package top.misspro.valheimadminsocket.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import top.misspro.valheimadminsocket.message.Action;
import top.misspro.valheimadminsocket.message.Response;

/**
 * @author liulinbo
 */
@Slf4j
public class ChannelUtils {

    public static void sendToClient(Channel channel, Action.Client code, Object data, String msg) {
        if (channel != null) {
            Response response = Response.builder()
                    .code(code.getValue())
                    .data(data)
                    .message(msg)
                    .build();
            try {
                channel.writeAndFlush(new TextWebSocketFrame(JSON.toJsonString(response)));
                log.debug("发送给客户端消息: {}", response);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
                log.error("消息编码失败");
                e.printStackTrace();
            }
        }
    }

    public static String getChannelId(Channel channel) {
        return channel.id().asShortText();
    }

}
